package itsm.isperp.module.controller.sparepartOld;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataRequest;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.TreeNodeUtils;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.configuration.ConfCategory;
import itsm.isperp.module.entity.sparepart.SptSparepart;
import itsm.isperp.module.entity.sparepart.SptSparepartMinStockRule;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.configuration.ConfCategoryService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.sparepart.SptSparepartCategoryService;
import itsm.isperp.module.service.sparepart.SptSparepartChangeDetailService;
import itsm.isperp.module.service.sparepart.SptSparepartInDetailService;
import itsm.isperp.module.service.sparepart.SptSparepartService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 备件管理控制器
 * 
 * @author lizx
 * @date 2013-9-12
 */
@Controller
@RequestMapping("sparepart/sparepart/old")
public class SptSparepartOldController extends BaseController<SptSparepart> {

  @Autowired
  protected SptSparepartService sptSparepartService;

  @Autowired
  protected SptSparepartCategoryService sptSparepartCategoryService;

  @Autowired
  protected SptSparepartInDetailService sptSparepartInDetailService;

  @Autowired
  protected SptSparepartChangeDetailService sptSparepartChangeDetailService;

  @Override
  public SptSparepartService getService() {
    return sptSparepartService;
  }

  @Override
  public String getPageTitle() {
    return "备件管理";
  }

  @RequestMapping("/getConfCategorys")
  @ResponseBody
  public List<? extends ITreeNode> getConfCategorys(String sparepartId) {

    List<SptSparepartMinStockRule> list = sptSparepartService
        .getSparepartMinStockRule(sparepartId);

    ConfCategoryService confCategoryService = ContextHolder
        .getSpringBean("confCategoryService");

    List<ConfCategory> confCategorys = confCategoryService.findAll(
        new JqGridRequest().isPageable(false)).getContent();

    Set<String> set = new HashSet<String>();
    for (SptSparepartMinStockRule r : list)
      set.add(r.getConfCategoryId());

    for (ConfCategory c : confCategorys) {
      if (set.contains(c.getId())) {
        c.setChecked(true);
      }
    }
    List<ConfCategory> tree = TreeNodeUtils.parseFormList(confCategorys);

    return tree;
  }

  @RequestMapping("listDetail")
  @ResponseBody
  public PageResponse<Map<String, Object>> listDetail(JqGridRequest request,
      HttpServletRequest req) {

    String type = req.getParameter("sptType");
    String relationId = req.getParameter("relationId");
    if (StringUtils.isNotEmpty(type) && StringUtils.isNotEmpty(relationId)) {
      List<Map<String, Object>> list = null;
      if (type.equalsIgnoreCase("in")) // 入库
      {
        list = this.sptSparepartInDetailService
            .findAllDetailBySparepartInId(relationId);
      } else // 出库
      {
        list = this.sptSparepartChangeDetailService
            .findAllDetailByRelationId(relationId);
      }
      String selectedSpt = "";
      for (Map<String, Object> map : list) {
        selectedSpt = selectedSpt + "'"
            + map.get("spt_sparepart_id").toString() + "',";
      }
      if (selectedSpt.length() > 0) {
        selectedSpt = selectedSpt.substring(0, selectedSpt.length() - 1);
        request.addFilterRule("id", JqGridFilterRuleOp.ni, selectedSpt);
      }

    }

    return this.getService().findAllDetailByRequest(request);

  }

  @Override
  @RequestMapping("edit")
  public ModelAndView edit(String id, HttpServletRequest req) throws Exception {
    ModelAndView mv = new ModelAndView("sparepart/sparepart/old/edit");

    String categoryId = req.getParameter("categoryId");
    String categoryName = "";
    SptSparepart model = null;
    if (StringUtils.isEmpty(id)) {
      model = new SptSparepart();
      model.setId(HibernateUUIDGenerator.generate());
      if (StringUtils.isNotEmpty(categoryId)) {
        model.setSptSparepartCategoryId(categoryId);
        categoryName = this.sptSparepartCategoryService.findOne(categoryId)
            .getName();
      }

    } else {
      model = this.getService().findOne(id);
      categoryName = this.sptSparepartCategoryService.findOne(
          model.getSptSparepartCategoryId()).getName();

    }
    String userName=ContextHolder.getLoginUsername();

    mv.addObject("categoryName", categoryName);
    mv.addObject("curUserName", userName);

    mv.addObject("model", model);

    return mv;
  }
  
  @RequestMapping("delete")
  @Override
  @ResponseBody
  public ResultMessage delete(String id, HttpServletRequest req)
  {
    JdbcTemplate jdbcTemplate = ContextHolder
        .getSpringBean("jdbcTemplate");
    String sql="select * from v_spt_process where id='"+id+"'";
    String deleteSql="";
    List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
    String url="";
    if(list.size()>0)
    {
      String type=list.get(0).get("spt_type").toString();
      switch(type)
      {
      case "备件归还":
        deleteSql="delete from spt_sparepart_back where id='"+id+"'";
        break;
      case "备件报废":
        deleteSql="delete from spt_sparepart_discard where id='"+id+"'";
        break;
      case "备件采购":
        deleteSql="delete from spt_sparepart_in where id='"+id+"'";
        break;
      case "备件领用":
        deleteSql="delete from spt_sparepart_out where id='"+id+"'";
        break;
      default:
      }
      jdbcTemplate.update(deleteSql);
      
    }
    return ResultMessage.newInstance(true);
    
  }

  @RequestMapping("save")
  @ResponseBody
  public ResultMessage save(SptSparepart model, HttpServletRequest req) {

    String categoryIdValue = req.getParameter("categoryIdValue");

    this.getService().deleteSparepartMinStockRule(model.getId());

    if (StringUtils.isNotBlank(categoryIdValue)) {

      ConfCategoryService confCategoryService = ContextHolder
          .getSpringBean("confCategoryService");
      DataRequest dr = new JqGridRequest().isPageable(true).setSelectColumns(
          "id,name");

      String[] categoryIds = categoryIdValue.split(",");

      List<String> list = new ArrayList<>();
      StringBuilder ins = new StringBuilder();

      int categoryIdsLength = categoryIds.length;

      if (categoryIdsLength > 0) {
        ins.append("'").append(categoryIds[0]).append("'");
        list.add(categoryIds[0]);
      }
      for (int i = 1; i < categoryIdsLength; i++) {
        list.add(categoryIds[i]);

        ins.append(",'").append(categoryIds[i]).append("'");

      }

      dr.addFilterRule("id", JqGridFilterRuleOp.in, ins.toString());
      this.getService().batchSaveSptSparepartMinStockRule(model.getId(), list);

      List<ConfCategory> confCategorys = confCategoryService.findAll(dr)
          .getContent();
      StringBuilder desc = new StringBuilder("在配置分类为( ");
      for (ConfCategory e : confCategorys) {
        desc.append(e.getName()).append(",");
      }

      desc.append(" ) 的配置项数目 除以 ").append(model.getMinStockUseRuleProportion());
      model.setMinStockUseRuleDesc(desc.toString());

    }

    this.getService()
        .saveOrUpdateAndSpecific(model, req, "minStockUseRuleDesc");
    return ResultMessage.newInstance(true, null, model.getId());
  }

  @RequestMapping("search")
  public ModelAndView search(JqGridRequest request, HttpServletRequest req)
      throws Exception {
    ModelAndView mv = new ModelAndView("sparepart/sparepart/old/search");
    ProjProjectService projProjectService = ContextHolder
        .getSpringBean("projProjectService");
    mv.addObject("projects", projProjectService.findAllPublished("id", "name"));

    return mv;
  }
  
  @RequestMapping("searchTotal")
  public ModelAndView searchTotal(JqGridRequest request, HttpServletRequest req)
      throws Exception {
    ModelAndView mv = new ModelAndView("sparepart/sparepart/old/searchTotal");
    return mv;
  }

  @RequestMapping("viewEdit")
  public ModelAndView viewEdit(String id, HttpServletRequest req)
      throws Exception {
    ModelAndView mv = new ModelAndView("sparepart/sparepart/old/viewEdit");

    JqGridRequest request = new JqGridRequest();
    request.addFilterRule("id", JqGridFilterRuleOp.eq, id);
    List<Map<String, Object>> list = sptSparepartService
        .findAllDetailByRequest(request).getContent();
    if (list != null && list.size() > 0) {
      mv.addObject("model", list.get(0));
    } else {
      mv.addObject("model", null);
    }

    return mv;
  }

  @RequestMapping("inOutList")
  public ModelAndView inOutList(String sparepartId, HttpServletRequest req)
      throws Exception {
    ModelAndView mv = this.getModelAndView();

    mv.addObject("id", sparepartId);
    return mv;
  }

  @RequestMapping("projectUsed")
  @ResponseBody
  public PageResponse<Map<String, Object>> projectUsed(String sparepartId,
      JqGridRequest request, HttpServletRequest req) {
    return sptSparepartService
        .findAllProjectUsedByRequest(sparepartId, request);
  }

  @RequestMapping("findSparepartProjectInUse")
  @ResponseBody
  public PageResponse<Map<String, Object>> findSparepartProjectInUse(
      String sparepartId, JqGridRequest request, HttpServletRequest req) {
    return sptSparepartService.findSparepartProjectInUse(request);
  }

  @RequestMapping("findSparepartProjectInUseExtend")
  @ResponseBody
  public PageResponse<Map<String, Object>> findSparepartProjectInUseExtend(
      JqGridRequest request, HttpServletRequest req) {
   String sparepartId=req.getParameter("sparepartId");
    if(StringUtils.isNoneBlank(sparepartId))
      request.addFilterRule("spt_sparepart_id",JqGridFilterRuleOp.eq,sparepartId);
    return sptSparepartService.findSparepartProjectInUseExtend(request);
  }
  
  @RequestMapping("findSparepartTotal")
  @ResponseBody
  public PageResponse<Map<String, Object>> findSparepartTotal(
      JqGridRequest request, HttpServletRequest req) {
    return sptSparepartService.findSparepartTotal(request);
  }

}
